<template>
  <basic-container>
    <avue-crud
      :option="option"
      :table-loading="loading"
      v-model="form"
      :data="data"
      :page.sync="page"
      :permission="permissionList"
      :before-open="beforeOpen"
      :row-class-name="tableRowClassName"
      ref="crud"
      @search-change="searchChange"
      @search-reset="searchReset"
      @selection-change="selectionChange"
      @current-change="currentChange"
      @size-change="sizeChange"
      @refresh-change="refreshChange"
      @on-load="onLoad"
    >
      <template slot="menu" slot-scope="{ row }">
        <el-button size="small" type="text" @click="iqcExamine(row.id)">检验</el-button>
      </template>
      <template slot="menuRight">
        <user-table-config :option="option" @confirm="(val) => handleSetUserConfig(val, pageCode)"></user-table-config>
      </template>
      <template slot="menuLeft">
        <el-button type="primary" size="small" @click="mergeCheck()">合并</el-button>
        <el-button size="small" type="primary" @click="handleUrgent()">加急</el-button>
      </template>
    </avue-crud>
    <el-dialog title="填写检验结果信息" append-to-body :visible.sync="showDialog" @close="closeDialog" class="iqcDialog" width="60%" :fullscreen="fullscreenDialog">
      <div slot="title">
        填写检验结果信息<i
          class="el-dialog__close fill-screen-icon"
          :class="fullscreenDialog ? 'el-icon-news' : 'el-icon-full-screen'"
          @click="fullscreenDialog = !fullscreenDialog"
        ></i>
      </div>
      <avue-form ref="properties" v-model="model" :option="propertiesOption">
        <template slot="examineResultLabel">
          <span class="view-style">&nbsp;IQC检验结果:</span>
        </template>

        <template slot="checkReport">
          <div>
            <label>
              <span style="color: #f56c6c" class="required text-danger">*</span>
              <span class="view-style">&nbsp;IQC检验报告:</span>
              <span class="iqc-placeholder">&nbsp;（支持图片）</span>
            </label>
          </div>
        </template>
        <template slot="remarkLabel">
          <span class="view-style">&nbsp;备注:</span>
        </template>
      </avue-form>
      <div slot="footer">
        <el-button type="primary" size="small" icon="el-icon-circle-plus-outline" @click="submit" v-preventReClick>保存</el-button>
        <el-button size="small" icon="el-icon-circle-close" @click="cancel">取消</el-button>
      </div>
    </el-dialog>
  </basic-container>
</template>

<script>
import { getList, getDetail, inspect, mergeCheck, urgent } from '@/api/quality/iqc-examine';
import { mapGetters } from 'vuex';
import userTableConfig from '@/components/user-table-config/index.vue';
import userConfig from '@/mixins/userConfig';
export default {
  components: {
    userTableConfig
  },
  mixins: [userConfig()],
  data() {
    return {
      fullscreenDialog: false, //dialog是否全屏
      pageCode: 'IQC_EXAMINE',
      form: {},
      model: {},
      query: {},
      loading: true,
      page: {
        pageSize: 20,
        currentPage: 1,
        total: 0
      },
      selectionList: [],
      data: [],
      selectData: [],
      code: '00',
      searchLabelWidth: 100,
      checkIqc: true,
      option: {
        height: 'calc(100vh - 486px)',
        calcHeight: 30,
        tip: false,
        searchShow: true,
        border: true,
        index: true,
        indexLabel: '序号',
        viewBtn: false,
        addBtn: false,
        delBtn: false,
        editBtn: false,
        selection: true,
        menu: false,
        dialogClickModal: false,
        labelWidth: 120,
        searchMenuSpan: 12,
        searchMenuPosition: 'right',
        searchLabelWidth: 90,
        menuWidth: 200,
        columnBtn: false,
        column: [
          {
            label: '检验单号',
            prop: 'documentNo',
            search: true,
            searchOrder: 1,
            order: 1,
            rules: [
              {
                required: true,
                message: '请输入送检单号',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '单据号',
            prop: 'sheetNo',
            order: 2,
            searchOrder: 4,
            search: true,
            rules: [
              {
                required: true,
                message: '请输入单据号',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '单据行号',
            prop: 'sheetLot',
            order: 3,
            rules: [
              {
                required: true,
                message: '请输入单据行号',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '是否加急',
            prop: 'isUrgent',
            hide: true,
            order: 19,
            rules: [
              {
                required: true,
                message: '请输入是否加急',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '物料编码',
            prop: 'partNo',
            searchOrder: 2,
            search: true,
            order: 2,
            rules: [
              {
                required: true,
                message: '请输入物料编码',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '物料名称',
            prop: 'partName',
            searchOrder: 3,
            search: true,
            order: 4,
            rules: [
              {
                required: true,
                message: '请输入物料名称',
                trigger: 'blur'
              }
            ]
          },
          // {
          //   label: '物料批次',
          //   prop: 'lotNo',
          //   order: 5,
          //   rules: [
          //     {
          //       required: true,
          //       message: '请输入物料批次',
          //       trigger: 'blur'
          //     }
          //   ]
          // },
          {
            label: '物料规格',
            prop: 'partModel',
            order: 6,
            rules: [
              {
                required: true,
                message: '请输入物料规格',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '送检数量',
            prop: 'sendExamineQuantity',
            order: 7,
            rules: [
              {
                required: true,
                message: '请输入送检数量',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '检验方式',
            prop: 'examineMode',
            order: 8,
            type: 'select',
            dicUrl: '/api/blade-system/dict/dictionary?code=inspection_mode',
            props: {
              label: 'dictValue',
              value: 'dictKey'
            },
            rules: [
              {
                required: true,
                message: '请输入检验方式',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '供应商代码',
            search: true,
            searchOrder: 5,
            prop: 'partnerCode',
            order: 16,
            rules: [
              {
                required: true,
                message: '请输入供应商代码',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '供应商名称',
            prop: 'partnerName',
            order: 17,
            rules: [
              {
                required: true,
                message: '请输入供应商名称',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '送检日期',
            prop: 'sendExamineDate',
            search: true,
            searchOrder: 20,
            searchSpan: 6,
            type: 'date',
            searchType: 'daterange',
            order: 18,
            format: 'yyyy-MM-dd',
            valueFormat: 'yyyy-MM-dd',
            startPlaceholder: '开始日期',
            endPlaceholder: '结束日期'
          }
        ]
      },
      showDialog: false, //IQC检验结果模态框
      propertiesOption: {
        emptyBtn: false,
        submitBtn: false,
        column: [
          {
            label: 'IQC检验结果',
            labelslot: true,
            prop: 'examineResult',
            span: 20,
            require: true,
            labelWidth: '160',
            type: 'radio',
            value: 'OK',
            dicData: [
              {
                label: 'OK',
                value: 'OK'
              },
              {
                label: 'NG',
                value: 'NG'
              }
            ],
            rules: [
              {
                required: true,
                message: '请选择IQC检验结果',
                trigger: 'blur'
              }
            ]
          },
          {
            label: 'IQC检验报告',
            prop: 'iqcAttachments',
            type: 'upload',
            span: 20,
            labelWidth: '160',
            loadText: '图片上传中，请稍等',
            propsHttp: {
              url: 'link',
              name: 'attachId',
              res: 'data'
            },
            listType: 'picture',
            limit: 3,
            accept: 'image/png, image/jpeg, image/jpg',
            tip: '只能上传png/jpeg/jpg文件',
            action: '/api/blade-resource/oss/endpoint/put-file-attach',
            rules: [
              {
                required: true,
                message: '请上传IQC检验报告',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '备注/原因',
            prop: 'remark',
            span: 20,
            type: 'textarea',
            labelWidth: '160',
            maxRows: 3,
            minRows: 3,
            rules: [
              {
                message: '请填写备注/原因',
                trigger: 'blur'
              }
            ]
          }
        ]
      }
    };
  },
  computed: {
    ...mapGetters(['permission']),
    permissionList() {
      return {};
    },
    ids() {
      let ids = [];
      this.selectionList.forEach((ele) => {
        ids.push(ele.id);
      });
      return ids.join(',');
    }
  },
  mounted() {
    this.$nextTick(() => {
      this.$structuralSplit();
    });
  },
  methods: {
    handleUrgent() {
      if (this.selectionList.length === 0) {
        this.$message({
          type: 'warning',
          message: '请选择检验单!'
        });
        return;
      }
      this.$confirm('确认对检验单进行加急?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          console.log(this.ids, 88888);
          return urgent(this.ids)
            .then((res) => {
              this.$message({
                type: 'success',
                message: '操作成功!'
              });
            })
            .catch((err) => {});
        })
        .then(() => {
          this.onLoad(this.page);
          this.$refs.crud.toggleSelection();
        });
    },
    tableRowClassName({ row, rowIndex }) {
      console.log(row.isUrgent, 44444);
      if (row.isUrgent) {
        return 'urgent-select-row';
      }
      return '';
    },
    /**
     * 提交检验结果
     */
    async submit() {
      // this.model.extFields = null;
      let attribute = this.model;
      let done;
      let validDate = await new Promise((resolve, reject) => {
        this.$refs.properties.validate((valid, done) => {
          done = done;
          if (valid) {
            resolve();
            done();
          } else {
          }
        });
      });
      Promise.all([validDate]).then(() => {
        attribute.examineResult === 'OK' ? (attribute.status = 3) : (attribute.status = 2);
        attribute.attachments = attribute.iqcAttachments.map((attachment) => {
          return {
            link: attachment.value,
            attachmentId: attachment.label,
            type: 'INSPECTION'
          };
        });
        inspect(attribute).then(
          () => {
            this.onLoad(this.page);
            this.$message({
              type: 'success',
              message: '操作成功!'
            });
            this.$refs.properties.resetForm();
            this.showDialog = false;
          },
          (error) => {
            window.console.log(error);
          }
        );
        done();
      });
    },

    cancel() {
      this.showDialog = false;
      this.model = {};
    },

    beforeOpen(done, type) {
      if (['edit', 'view'].includes(type)) {
        getDetail(this.form.id).then((res) => {
          this.form = res.data.data;
        });
      }
      done();
    },
    searchReset() {
      // this.query = { status: 1 };
      this.onLoad(this.page);
    },
    searchChange(params, done) {
      if (params.sendExamineDate && params.sendExamineDate.length > 0) {
        params.startSendExamineDate = params.sendExamineDate[0];
        params.endSendExamineDate = params.sendExamineDate[1];
        // let startSendExamineDate = new Date(params.sendExamineDate[0]);
        // startSendExamineDate.setHours(0, 0, 0);
        // let endSendExamineDate = new Date(params.sendExamineDate[1]);
        // endSendExamineDate.setHours(23, 59, 59);
        // params.startSendExamineDate = this.$moment(startSendExamineDate).format('YYYY-MM-DD  HH:mm:ss');
        // params.endSendExamineDate = this.$moment(endSendExamineDate).format('YYYY-MM-DD  HH:mm:ss');
      }
      delete params.sendExamineDate;
      // params.status = 1;
      this.query = params;
      this.page.currentPage = 1;
      this.onLoad(this.page, params);
      done();
    },
    selectionChange(list) {
      this.selectionList = list;
    },
    selectionClear() {
      this.selectionList = [];
      this.$refs.crud.toggleSelection();
    },
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
    },
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
    },
    refreshChange() {
      this.onLoad(this.page, this.query);
    },
    onLoad(page, params = {}) {
      this.loading = true;
      params.documentType = 'IQC';
      params.statusStr = '1,4';
      params.isUrgentDesc = true;
      getList(page.currentPage, page.pageSize, Object.assign(params, this.query)).then((res) => {
        const data = res.data.data;
        this.page.total = data.total;
        // [] || dataListTable
        this.data = data.records;
        this.loading = false;
        this.selectionClear();
      });
    },

    closeDialog() {
      this.$refs.properties.resetForm();
    },
    //点击检验
    async iqcExamine(id) {
      this.model = {};
      this.showDialog = true;
      this.fullscreenDialog = false;
      getDetail(id).then((res) => {
        if (!res.data.data.examineResult) {
          res.data.data.examineResult = 'OK';
        }
        this.model = res.data.data;
      });
    },
    /*
     * 合并检验
     */
    mergeCheck() {
      if (this.selectionList.length < 2) {
        this.$message({
          type: 'warning',
          message: '请选择至少两条检验单!'
        });
        return;
      }
      this.$confirm('是否进行合并?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          return mergeCheck(this.ids)
            .then((res) => {
              this.$message({
                type: 'success',
                message: '合并成功!'
              });
            })
            .catch((err) => {});
        })
        .then(() => {
          this.onLoad(this.page);
          this.$refs.crud.toggleSelection();
        });
    }
  }
};
</script>

<style scoped lang="scss">
$size: 16px;
.view-style {
  font-weight: bold;
  font-size: $size;
}
.iqc-placeholder {
  font-size: $size;
  color: #aaaaaa;
}
.iqcDialog {
  ::v-deep input[type='file'] {
    display: none !important;
  }
  ::v-deep .el-form-item__label {
    font-weight: bold;
    font-size: 16px;
  }
}
$BORDER-STYLE: 1px solid #f0f0f0 !important;
::v-deep .inspection-btn:hover {
  background-color: #dedede;
}
::v-deep .el-dialog__header {
  border-bottom: $BORDER-STYLE;
}

::v-deep .el-dialog__footer {
  border-top: $BORDER-STYLE;
}

.fill-screen-icon {
  color: #909399;
  font-size: 15px;
  float: right;
  padding-right: 25px;
  &:hover {
    color: #409eff;
  }
}

.group-title {
  border-bottom: 1px solid rgb(240, 240, 240) !important;
  font-size: 16px;
  font-weight: 500;
  height: 50px;
  line-height: 50px;
  color: rgba(0, 0, 0, 0.85);
  margin-bottom: 20px;
}
::v-deep .urgent-select-row {
  color: red;
}
</style>
